
package com.axc.gallery2.net.activity;

import java.util.ArrayList;
import java.util.List;


import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery.LayoutParams;

import com.axc.gallery2.R;
import com.axc.gallery2.dbhelper.NetAlbumDHhelper;
import com.axc.gallery2.dbhelper.NetAlbumInfo;
import com.axc.gallery2.net.ApiInvoker;
import com.axc.gallery2.net.CheckNetworkState;
import com.axc.gallery2.view.NetAlbumGridViewAdapter;
import com.renren.api.connect.android.AsyncRenren;
import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.common.AbstractRequestListener;
import com.renren.api.connect.android.exception.RenrenAuthError;
import com.renren.api.connect.android.exception.RenrenError;
import com.renren.api.connect.android.photos.AlbumBean;
import com.renren.api.connect.android.photos.AlbumGetRequestParam;
import com.renren.api.connect.android.photos.AlbumGetResponseBean;
import com.renren.api.connect.android.view.RenrenAuthListener;

public class NetAlbumsActivity extends BaseActivity {

    // 人人相网应用API_KEY
    private static final String API_KEY = "ac64dbb8986a4282ab86834960cc255c";

    private static final String SECRET_KEY = "c62851d495c843dc822b1396dfa2ea63";

    private static final String APP_ID = "2080882";
    
    //请求用户权限
    public static final String[] USER_PERMISSIONS = { "publish_feed",
        "create_album", "photo_upload", "read_user_album", "status_update","read_user_photo" };

    private Renren renren;

    private Handler handler;

    private LinearLayout mainLayout;

    // 检查网络状态
    private CheckNetworkState checkNetworkState;

    private GridView gridView;

    private NetAlbumGridViewAdapter netGridViewAdapter;

    private int w = 0;// GridView长和宽

    // 进度对话框
   // private GalleryProgressDialog galleryProgressDialog;

   // private Context context;

    private List<AlbumBean> albumList = new ArrayList<AlbumBean>();

    /**
     * 调用获取相册API接口需传入的参数
     */
    AlbumGetRequestParam albumGetRequestParam = new AlbumGetRequestParam();

    // 相册的文字标题
    //private String[] titles;

    private List<NetAlbumInfo> netAlbumInfos;

    public NetAlbumsActivity() {
        //context = this;
    }

    public View makeView() {
        ImageView imageView = new ImageView(this);
        imageView.setBackgroundColor(0xFF000000);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        return imageView;
    }

  //主题应用
	public static NetAlbumsActivity Talbum;
	public int theme = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 主题
        Talbum = this;
        theme = getSharedPreferences("cons", MODE_PRIVATE).getInt("theme",
                android.R.style.Theme);
        setTheme(theme);
        super.onCreate(savedInstanceState);
        // 初始化标题文字
        titlebarText.setText(R.string.net_titlebar_netalbum);

        // 初始化人人网络相册
        renren = new Renren(getApiKey(), getSecretKey(), getAppId(), this);
        ApiInvoker.init(renren);
    

        handler = new Handler();
        initNetAlbum();
    }

    @Override
    protected void onResume() {
        super.onResume();
        renren.init(this);
    }

    /**
     * 启动网络相册主界面
     */
   /* private void startNetAlbums() {
        Intent intent = new Intent(this, NetAlbumsActivity.class);
        intent.putExtra(Renren.RENREN_LABEL, renren);
        startActivity(intent);
    }*/

    /**
 * 
 */
    Thread thread = new Thread() {

        @Override
        public void run() {
            System.out.println("run");

            NetAlbumDHhelper netAlbumDHhelper = new NetAlbumDHhelper(getBaseContext());
            netAlbumInfos = netAlbumDHhelper.getNetAlbums();
            handlerResultHandler.sendEmptyMessage(0);

            while (true) {

                if (albumList.size() != 0) {

                    System.out.println("handlerResultHandler");
                    handlerResultHandler.sendEmptyMessage(1);
                    return;
                }
            }

        }
    };
    Handler handlerResultHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            System.out.println("handleMessage");
            gridView = (GridView) findViewById(R.id.net_gridview);
            //单击事件
            gridView.setOnItemClickListener(new OnItemClickListener()  {

                private String aid;
                private String ablumName;

                @Override
                public void onItemClick(AdapterView<?> arg0, View View, int _position,
                        long arg3) {
                    aid = ((TextView)View.findViewById(R.id.net_ablums_folder_aid)).getText().toString();
                    ablumName =((TextView)View.findViewById(R.id.net_ablums_folder_title)).getText().toString();
                    System.out.println(aid);
                    Intent intent = new Intent(NetAlbumsActivity.this, NetAlbumActivity.class);
                    Bundle bundle= new Bundle();
                    bundle.putString("aid", aid);
                    bundle.putString("ablumName", ablumName);
                    intent.putExtras(bundle);
                    intent.putExtra("renren",renren);
                    startActivity(intent);
                }

            });
            w = (getWindowManager().getDefaultDisplay().getWidth() - 24) / 3;
            switch (msg.what) {
                case 0:
                    System.out.println("4");
                    System.out.println("5");
                    netGridViewAdapter = new NetAlbumGridViewAdapter(NetAlbumsActivity.this,
                            netAlbumInfos);
                    netGridViewAdapter.setGridviewSize(w);
                    gridView.setAdapter(netGridViewAdapter);
                    System.out.println("6");
                    break;
                case 1:
                    System.out.println("1");
                    if (albumList.size() > 0) {
                        System.out.println("2");
                        netAlbumInfos.clear();
                        for (AlbumBean albumBean : albumList) {
                            netAlbumInfos.add(new NetAlbumInfo(albumBean));
                            System.out.println("albumBean.getPhotos().size()"+albumBean.getPhotos().size());
                        }
                        if (netAlbumInfos.size() > 0) {
                            System.out.println("3");
                            netGridViewAdapter.clearConvertView();
                            netGridViewAdapter.set_netAlbumInfos(netAlbumInfos);
                            netGridViewAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 初始化网络相册
     */
    private void initNetAlbum() {

        final RenrenAuthListener listener = new RenrenAuthListener() {

            @Override
            public void onComplete(Bundle values) {

                // 调用SDK异步接口获取相册
                new AsyncRenren(renren).getAlbums(albumGetRequestParam,
                        new AbstractRequestListener<AlbumGetResponseBean>() {
                        @Override
                    public void onRenrenError(
                            final RenrenError renrenError) {
                        NetAlbumsActivity.this
                                .runOnUiThread(new Runnable() {
                                @Override
                            public void run() {

                                dismissProgress();
                                }
                                                        });
                        }

                    @Override
                    public void onFault(final Throwable fault) {
                        NetAlbumsActivity.this
                                .runOnUiThread(new Runnable() {
                                @Override
                            public void run() {
                                                                // 查询出错，结束进度框，显示错误信息
                                dismissProgress();
                                }
                                                        });
                        }

                    @Override
                    public void onComplete(
                            final AlbumGetResponseBean bean) {
                        NetAlbumsActivity.this
                                .runOnUiThread(new Runnable() {
                                @Override
                            public void run() {
                                albumList = bean.getAlbums();
                                //bean.getAlbums().get(0).getPhotos();
                                new AsyncTask<Object, Void, Void>() {

                                    @SuppressWarnings("unchecked")
                                    @Override
                                    protected Void doInBackground(Object... params) {
                                        List<AlbumBean> list = (List<AlbumBean>) params[0];
                                        NetAlbumDHhelper netAlbumDHhelper = new NetAlbumDHhelper(
                                                getBaseContext());
                                        netAlbumDHhelper.clearAlbum();
                                        for (AlbumBean albumBean : list) {
                                            netAlbumDHhelper.addNetAlbum(albumBean);
                                        }
                                        return null;
                                    }

                                }.execute(albumList);
                                                                //                                
                                // System.out.println("albumList size:" +
                                // albumList.size());
                                // System.out.println("bean size:" +
                                // bean.getAlbums().size());
                            }
                                                        });

                    }
                                        });

            }

            @Override
            public void onRenrenAuthError(
                    RenrenAuthError renrenAuthError) {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        System.out.println("查询出错，结束进度框，显示错误信息3");
                        Toast.makeText(NetAlbumsActivity.this,
                                NetAlbumsActivity.this.getString(R.string.auth_failed),
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onCancelLogin() {
            }

            @Override
            public void onCancelAuth(Bundle values) {
            }

        };

        /** 检测网络连接 **/
        System.out.println("检测网络连接 122222");
        
        checkNetworkState = new CheckNetworkState(this);

        int state = checkNetworkState.NetworkState();
        System.out.println("检测网络连接: " + state);
        switch (state) {
            case 0:
                // 2G、3G网络正常
            	  // wifi网络正常
                thread.start();
                mainLayout = (LinearLayout) getLayoutInflater().inflate(
                        R.layout.net_album_folder_gridview, null);
                root.addView(mainLayout);
                renren.authorize(NetAlbumsActivity.this, USER_PERMISSIONS,listener);
                //System.out.println("检测网络连接 size:" + albumList.size());
                break;
            case 1:
                // wifi网络正常
                thread.start();
                mainLayout = (LinearLayout) getLayoutInflater().inflate(
                        R.layout.net_album_folder_gridview, null);
                root.addView(mainLayout);
                renren.authorize(NetAlbumsActivity.this, USER_PERMISSIONS,listener);
                //System.out.println("检测网络连接 size:" + albumList.size());
                break;
            case -1:
                checkNetworkState.setNetworkTips();
                mainLayout = (LinearLayout) getLayoutInflater().inflate(
                        R.layout.net_without_connection_layout, null);
                root.addView(mainLayout);
                break;
            default:
                break;
        }

    }

	public static String getSecretKey() {
		return SECRET_KEY;
	}

	public static String getApiKey() {
		return API_KEY;
	}

	public static String getAppId() {
		return APP_ID;
	}

	/**
	 * 登出
	 */
	@Override
	protected void LoadOut() {
		try {
			renren.logout(NetAlbumsActivity.this);
			Intent intent =new Intent();
			intent.setClass(NetAlbumsActivity.this, NetAlbumsActivity.class);
			NetAlbumsActivity.this.startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if(event.getAction()==KeyEvent.KEYCODE_BACK){
			this.finish();//返回
		}
		return super.onKeyUp(keyCode, event);
	}
}
